package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String login(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String userType,
            HttpSession session) {

        User user = userService.authenticate(username, password, userType);

        if (user != null) {
            session.setAttribute("loggedIn", true);
            session.setAttribute("username", username);
            session.setAttribute("userType", userType);

            // 根据用户类型重定向到不同页面
            switch (userType) {
                case "student":
                    return "redirect:/student/students";
                case "teacher":
                    return "redirect:/teachers/courses";
                case "admin":
                    return "redirect:/admin/dashboard";
                default:
                    return "redirect:/index.jsp?error=true";
            }
        } else {
            return "redirect:/index.jsp?error=true";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index";
    }
}